// Copyright (c) 2023 Presto Labs Pte. Ltd.
// Author: leon

#pragma once

#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <vector>

#include "coin2/exchange/base/symbology/index_product.h"
#include "coin2/exchange/base/symbology/util.h"
#include "coin2/exchange/deribit_index/symbology/currency.h"

namespace coin2::exchange::deribit_index::symbology {

class DeribitIndexProduct : public base::symbology::IndexProduct<DeribitCurrency, DeribitIndexProduct>,
                            public base::symbology::ProductFromStrMixin<DeribitIndexProduct> {
 public:
  DeribitIndexProduct(
      const DeribitCurrency& base,
      const DeribitCurrency& quote)
      : IndexProduct(
            base,
            quote,
            ToNativeProduct(base, quote),
            ToNativeProduct(base, quote),
            base::market::ExchangeType::Deribit) {}

 public:
  static std::unique_ptr<DeribitIndexProduct> FromNativeStrImpl(
      const std::string& native_product,
      int64_t resolve_timestamp) {
    std::unique_ptr<DeribitCurrency> base_ptr;
    std::unique_ptr<DeribitCurrency> quote_ptr;
    bool success = ParseNativeProduct(
        native_product, resolve_timestamp, &base_ptr, &quote_ptr);
    if (success) {
      return std::make_unique<DeribitIndexProduct>(
          *base_ptr, *quote_ptr);
    } else {
      return {};
    }
  }

 private:
  static bool ParseNativeProduct(
      const std::string& product_str,
      int64_t resolve_timestamp,
      std::unique_ptr<DeribitCurrency>* base_ptr,
      std::unique_ptr<DeribitCurrency>* quote_ptr) {
    std::vector<std::string> splitted;
    splitted = Split(product_str, "_");
    if (splitted.size() != 2) {
      return false;
    }
    *base_ptr = DeribitCurrency::FromNativeStrNoThrow(splitted[0], resolve_timestamp);
    *quote_ptr = DeribitCurrency::FromNativeStrNoThrow(splitted[1], resolve_timestamp);
    return true;
  }

  static std::string ToNativeProduct(
      const DeribitCurrency& base,
      const DeribitCurrency& quote) {
    using base::market::MarketType;
    std::stringstream ss;
    ss << base.native_currency(MarketType::Spot) << '_'
       << quote.native_currency(MarketType::Spot);
    return ss.str();
  }
};
}  // namespace coin2::exchange::deribit_index::symbology
